package com.ruoyi.dm.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dm.domain.RadioStationParam;
import com.ruoyi.dm.domain.RadioStationVO;
import com.ruoyi.dm.domain.po.RadioStationPO;
import com.ruoyi.dm.mapper.RadioStationInfoMapper;
import com.ruoyi.dm.service.IRadioStationInfoService;
import com.ruoyi.utils.TranferUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class RadioStationInfoImpl extends ServiceImpl<RadioStationInfoMapper, RadioStationPO> implements IRadioStationInfoService {

    @Autowired
    private RadioStationInfoMapper radioStationInfoMapper;

    @Override
    public IPage<RadioStationVO> query(RadioStationParam queryParam) {
        LambdaQueryWrapper<RadioStationPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(queryParam.getFileName()),RadioStationPO::getName,queryParam.getFileName());
        //按年查询
        if (null != queryParam.getStartDate() && null != queryParam.getEndDate()) {
            int start = DateUtil.truncate(queryParam.getStartDate(), DateField.YEAR).getField(DateField.YEAR);
            int end = DateUtil.truncate(queryParam.getEndDate(), DateField.YEAR).getField(DateField.YEAR);
            queryWrapper.ge( RadioStationPO::getStartYear, start);
            queryWrapper.le(RadioStationPO::getEndYear, end);
        }
        queryWrapper.orderByDesc(RadioStationPO::getStartYear);
        IPage page = page(queryParam.page(), queryWrapper);
        List<RadioStationVO> objects = new ArrayList<>();
        for (Object airCollectRecordPO : page.getRecords()) {
            RadioStationPO po = (RadioStationPO) airCollectRecordPO;
            RadioStationVO airCollectVO = TranferUtils.tranferRadioStationPO(po);
            objects.add(airCollectVO);
        }
        page.setRecords(objects);
        return page;
    }

    @Override
    public boolean input(MultipartFile[] files) {
        try {
            for (MultipartFile multipartFile : files) {
                InputStream inputStream = multipartFile.getInputStream();
                ExcelUtil<RadioStationPO> excelUtil = new ExcelUtil<RadioStationPO>(RadioStationPO.class);
                List<RadioStationPO> pos = excelUtil.importExcel(inputStream, 0);
                if (null != pos) {
                    LocalDateTime now = LocalDateTime.now();
                    for (RadioStationPO po : pos) {
                        po.setCreateDate(now);
                    }
                    saveBatch(pos);
                }
            }
            //剔除重复的
            radioStationInfoMapper.deleteRepeate();
            updateStationList();
        } catch (Exception e) {
            log.error("导入异常",e);
            throw new ServiceException("导入异常");
        }
        return false;
    }

    @Override
    public boolean delFile(Long id) {
        removeById(id);
        return true;
    }

    @Override
    public boolean delBatch(List<Long> delParam) {
        removeBatchByIds(delParam);
        return true;
    }

    @Override
    public String export() {
        List<RadioStationPO> radioStationPOS = list();
        ExcelUtil<RadioStationPO> excelUtil = new ExcelUtil<RadioStationPO>(RadioStationPO.class);
        AjaxResult result = excelUtil.exportExcel(radioStationPOS, "无线电探空站点");
        String filename =(String) result.get("data");
        String filePath = RuoYiConfig.getDownloadPath() + filename;
        return filePath;
    }

    @Override
    public boolean edit(RadioStationVO vo)  {
        RadioStationPO radioStationPO = new RadioStationPO();
        radioStationPO.setLat(vo.getLat());
        radioStationPO.setLon(vo.getLon());
        radioStationPO.setHight(vo.getHight());
        radioStationPO.setDetail(vo.getDetail());
        radioStationPO.setName(vo.getName());
        radioStationPO.setStartYear(vo.getStartYear());
        radioStationPO.setEndYear(vo.getEndYear());
        radioStationPO.setTotalDay(vo.getTotalDay());
        radioStationPO.setCreateDate(LocalDateTime.now());
        if (null != vo.getId()) {
            radioStationPO.setId(vo.getId());
            updateById(radioStationPO);
        }else {
            save(radioStationPO);
        }
        updateStationList();
        return true;
    }

    /**
     * 脚本调用需要用到这个文本
     */
    public void updateStationList() {
        //将站点写入到文本中 /dgdq/code/dgdq-algorithm/collect/igra2-station-list.txt
        File file = new File("/dgdq/code/dgdq-algorithm/collect/igra2-station-list.txt");
        List<RadioStationPO> list = list();
        List<String> lines = new ArrayList<>(list.size());
        for (RadioStationPO stationPO : list) {
            //ACM00078861  17.1170  -61.7830   10.0    COOLIDGE FIELD (UA)            1947 1993  13896
            StringBuilder append = new StringBuilder()
                    .append(stationPO.getName()).append(" ")
                    .append(stationPO.getLon()).append(" ")
                    .append(stationPO.getLat()).append(" ")
                    .append(stationPO.getHight()).append(" ")
                    .append(stationPO.getDetail()).append(" ")
                    .append(stationPO.getStartYear()).append(" ")
                    .append(stationPO.getEndYear()).append(" ")
                    .append(stationPO.getTotalDay());
            lines.add(append.toString());
        }
        FileUtil.writeLines(lines,file,"UTF-8");
    }

    @Override
    public String modelExport() {
        File template = new File(RuoYiConfig.getDownloadPath() + "无线电探空站点导出模板.xls");
        if (template.isFile()) {
            //存在模板 直接返回
        }else {
            ExcelUtil<RadioStationPO> excelUtil = new ExcelUtil<RadioStationPO>(RadioStationPO.class);
            AjaxResult result = excelUtil.exportExcel(ListUtil.empty(), "无线电探空站点");
            String filename = (String) result.get("data");
            String filePath = RuoYiConfig.getDownloadPath() + filename;
            FileUtil.copy(new File(filePath), template, true);
        }
        return template.getAbsolutePath();
    }
}
